package org.glorylight.hacks.social.service;

import java.util.Date;
import java.util.UUID;

import org.glorylight.hacks.social.model.ScrapBook;
import org.glorylight.hacks.social.model.ScrapBookComments;
import org.glorylight.hacks.social.model.User;
import org.glorylight.hacks.social.model.Voter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly = true)
public class CommentService extends BaseService {
	
	private static final Logger log = LoggerFactory.getLogger(CommentService.class);
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private ScrapBookService scrapBookService;
	
	@Transactional(readOnly = false)
	public void addComment(String emailId, UUID scrapId, String comment) throws Exception {
		log.debug("adding comment for scrap : {}", scrapId);
		User user = userService.findUserForCredential(emailId);
		ScrapBook scrapBook = em.find(ScrapBook.class, scrapId);
		Voter voter = new Voter(user.getFirstName(), user.getLastName(), user.getUserId());
		ScrapBookComments scrapComment = new ScrapBookComments(UUID.randomUUID(), scrapBook, voter, comment, new Date());
		scrapBook.getComments().add(scrapComment);
		add(scrapBook);
	}
	
	@Transactional(readOnly = false)
	public void updateComment(String emailId, UUID commentId, String newComment) throws Exception {
		log.debug("updating user comment");
		User user = userService.findUserForCredential(emailId);
		ScrapBookComments scrapBookComments = em.find(ScrapBookComments.class, commentId);
		Voter voter = scrapBookComments.getVoter();
		if(voter.getUserId().equals(user.getUserId())) {
			scrapBookComments.setComment(newComment);
			update(scrapBookComments);
		}
	}
	
	@Transactional(readOnly = false)
	public void deleteComment(String emailId, UUID commentId) throws Exception {
		log.debug("delete user comment");
		User user = userService.findUserForCredential(emailId);
		ScrapBookComments scrapBookComments = em.find(ScrapBookComments.class, commentId);
		Voter voter = scrapBookComments.getVoter();
		if(voter.getUserId().equals(user.getUserId()) || scrapBookComments.getScrapBook().getUserId().equals(user.getUserId())) {
			delete(scrapBookComments);
		}
	}
	
}
